package com.heima.wemedia.service.impl;

import cn.hutool.core.collection.CollUtil;
import com.baomidou.mybatisplus.extension.service.impl.ServiceImpl;
import com.heima.model.wemedia.pojos.WmSensitive;
import com.heima.utils.common.SensitiveWordUtil;
import com.heima.wemedia.mapper.WmSensitiveMapper;
import com.heima.wemedia.service.WmSensitiveService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.stereotype.Service;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;
import java.util.stream.Collectors;

@Service
public class WmSensitiveServiceImpl extends ServiceImpl<WmSensitiveMapper, WmSensitive> implements WmSensitiveService {



    @Autowired
    private StringRedisTemplate redisTemplate;

    @Override
    public boolean keySensitive(String text) {

        List<String> sensitiveWordList = new ArrayList<>();
        //从redis缓存中获取敏感词列表
        sensitiveWordList = redisTemplate.opsForList().range("sensitive_words", 0, -1);
        if(CollUtil.isEmpty(sensitiveWordList)){
            //从数据中获取敏感词列表
            List<WmSensitive> wmSensitiveList = this.list();
            sensitiveWordList = wmSensitiveList.stream().map(WmSensitive::getSensitives).collect(Collectors.toList());
            //存入到redis缓存中
            redisTemplate.opsForList().leftPushAll("sensitive_words",sensitiveWordList);
        }
        //生成关键词字典库
        SensitiveWordUtil.initMap(sensitiveWordList);
        //获取匹配的关键词和命中次数
        Map<String, Integer> map = SensitiveWordUtil.matchWords(text);
        if(CollUtil.isNotEmpty(map)){
            return false;
        }
        return true;

    }
}
